<template>
    <div class="user-profile-container">
        <el-card class="profile-card">
            <!-- Title -->
            <div class="title">Personal Information</div>

            <!-- Tabs -->
            <el-tabs v-model="activeTab" class="profile-tabs">
                <el-tab-pane label="Basic information" name="basic" />
                <el-tab-pane label="Modify information" name="password" />
                <el-tab-pane label="Change Password" name="changepassword" />
            </el-tabs>

            <!-- Basic Info Form -->
            <div v-if="activeTab === 'basic'" class="form-section">
                <el-form label-width="150px">
                    <div class="hang-row">
                        <el-form-item label="User username:">
                            <span>{{ basicInfo.username }}</span>
                        </el-form-item>
                        <el-form-item label="User nickname:">
                            <span>{{ basicInfo.nickname }}</span>
                        </el-form-item>
                        <el-form-item></el-form-item>
                    </div>
                    <div class="hang-row">
                        <el-form-item label="phone number:">
                            <span>{{ basicInfo.phone }}</span>
                        </el-form-item>
                        <el-form-item label="User email:">
                            <span>{{ basicInfo.email }}</span>
                        </el-form-item>
                        <el-form-item></el-form-item>
                    </div>
                    <el-form-item label="userLevel:">
                        <span>{{ levelvalue }}</span>
                    </el-form-item>
                    <el-form-item label="Belonging role:">
                        <span>{{ basicInfo.rolestring }}</span>
                    </el-form-item>
                </el-form>

            </div>

            <!-- Password Change Form -->
            <div v-if="activeTab === 'password'" class="form-section">
                <el-form label-width="150px" :rules="userInforules">
                    <el-form-item label="User nickname">
                        <el-input v-model="userInfo.nickname" style="width: 240px" maxlength="30" />
                    </el-form-item>
                    <el-form-item label="gender">
                        <el-radio-group v-model="userInfo.gender">
                            <el-radio :value="0">male</el-radio>
                            <el-radio :value="1">female</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="Belonging address">
                        <el-select v-model="userInfo.contry" placeholder="country" style="width: 240px"
                            @change="handleCountryChange">
                            <el-option v-for="(item, index) in datasel" :key="index" :label="item.name"
                                :value="item.name" />
                        </el-select>
                        <el-select v-model="userInfo.addresszhou" placeholder="state/county" style="width: 240px"
                            :disabled="!userInfo.contry">
                            <el-option v-for="(state, index) in states" :key="index" :label="state.name"
                                :value="state.name" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="detailed address">
                        <el-input v-model="userInfo.account" style="width: 240px" />
                    </el-form-item>

                </el-form>
                <el-button type="primary" @click="changeperson">save</el-button>
                <el-button type="danger" @click="closechange">cancel</el-button>
            </div>
            <div v-if="activeTab === 'changepassword'" class="form-section">
                <el-form label-width="150px" :rules="changerule">
                    <el-form-item label="Original password">
                        <el-input v-model="changepassword.oldpassword" type="password" style="width: 240px"
                            maxlength="30" />
                    </el-form-item>
                    <el-form-item label="New Password">
                        <el-input v-model="changepassword.newpassword" type="password" style="width: 240px"
                            maxlength="30" />
                    </el-form-item>
                    <el-form-item label="Confirm password">
                        <el-input v-model="changepassword.newpasswordagain" type="password" style="width: 240px"
                            maxlength="30" />
                    </el-form-item>

                </el-form>
                <el-button type="primary" @click="confirmpassword">submit</el-button>
                <el-button type="danger" @click="close">cancel</el-button>
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import data from "@/untils/address/states.json"
const activeTab = ref('basic');
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { getUserBasicData, personcenterEditInfo, personcenterEditPass } from "@/api/api.js"
import { Decrypt, Encrypt } from '../../untils/passjs/security';
// import { use } from 'react';

let router = useRouter();
// Basic information
const basicInfo = ref({
    nickname: '',
    username: "",
    phone: '',
    email: '',
    belongingrole: [],
    rolestring: ''
});

// User information
const userInfo = ref({
    nickname: '',
    gender: 0,
    contry: "",
    addresszhou: '',
    account: '',
    userLevel: null
});
let userInforules = ref({
    nickname: [
        { required: true, message: 'Please input a nickname', trigger: 'blur' }
    ]
})
let changepassword = ref(
    {
        oldpassword: "",
        newpassword: "",
        newpasswordagain: ""
    }
)

let levelvalue = ref('')
function switchllevel(level) {
    switch (level) {
        case '0':
            levelvalue.value = 'T0'
            break;
        case '1':
            levelvalue.value = 'T1'
            break;
        case '2':
            levelvalue.value = 'T2'
            break;
        case '3':
            levelvalue.value = 'T3'
            break;
        case '4':
            levelvalue.value = 'T4'
            break;
        case '5':
            levelvalue.value = 'T5'
            break;
        case '6':
            levelvalue.value = 'T1'
            break;
        case '7':
            levelvalue.value = 'T2'
            break;
        case '8':
            levelvalue.value = 'T3'
            break;
        case '9':
            levelvalue.value = 'T4'
            break;
    }
}
async function confirmpassword() {

    if (changepassword.value.oldpassword == "" || changepassword.value.newpassword == "" || changepassword.value.newpasswordagain == "") {

        ElMessage.error("Please fill in the password")
        return;
    }
    if (changepassword.value.newpassword == changepassword.value.newpasswordagain) {
        console.log("密码修改成功", changepassword.value)
        // {"oldPassword":admin99992.....,"password":"admin99992......","confirmPassword":"admin99992......"}
        console.log(changepassword.value);
        let requestdata = {
            oldPassword: changepassword.value.oldpassword,
            password: changepassword.value.newpassword,
            confirmPassword: changepassword.value.newpasswordagain
        }
        console.log(Encrypt(JSON.stringify(requestdata)));
        console.log(Decrypt(Encrypt(JSON.stringify(requestdata))));

        let res = await personcenterEditPass(Encrypt(JSON.stringify(requestdata)));
        if (res.code == 200) {
            ElMessage.success(res.msg)
            changepassword.value.oldpassword = "";
            changepassword.value.newpassword = "";
            changepassword.value.newpasswordagain = "";
        }


    } else {
        ElMessage.error("The two passwords are inconsistent, please re-enter")
    }



}
let changerule = ref(
    {
        oldpassword: [
            {
                required: true,
                message: 'Please input a password',
                trigger: 'blur'
            },
            {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
                message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
                trigger: 'blur'
            }
        ],
        newpassword: [
            {
                required: true,
                message: 'Please input a password',
                trigger: 'blur'
            },
            {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
                message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
                trigger: 'blur'
            }
        ],
        newpasswordagain: [
            {
                required: true,
                message: 'Please input a password',
                trigger: 'blur'
            },
            {
                pattern: /^(?=.*[a-zA-Z])(?=.*\d)(?=.*[!@#$%^&*])[a-zA-Z\d!@#$%^&*]{8,16}$/,
                message: 'Password requires a combination of 8-16 letters, numbers, and special characters',
                trigger: 'blur'
            }
        ]
    }

)
// 国家列表数据
const datasel = ref([]);

// 州/省列表数据
const states = ref([]);
// 国家与州/省的映射关系
const countryStates = ref({});

function getuserbasicdatafun() {
    getUserBasicData().then(res => {
        console.log(res);
        if (res.code == 200) {
            basicInfo.value.nickname = res.data.user.nickname;
            basicInfo.value.username = res.data.user.username;
            basicInfo.value.userLevel = res.data.user.userLevel;
            if (res.data.user.phoneAreaCode == '') {
                basicInfo.value.phone = res.data.user.phone;
            }
            basicInfo.value.phone = `+${res.data.user.phoneAreaCode} ${res.data.user.phone}`;
            basicInfo.value.email = res.data.user.email;
            // basicInfo.value.belongingrole = res.data.roles || "None";
   
            const roleNames = res.data.roles.map(item => item.roleName);

 
            const uniqueRoleNames = [...new Set(roleNames)];

            basicInfo.value.rolestring = uniqueRoleNames.join(',');

            userInfo.value.nickname = res.data.user.nickname;
            userInfo.value.gender = res.data.user.gender;
            // userInfo.value.contry = res.data.user.area;
            // userInfo.value.contry = res.data.user.area;
            userInfo.value.account = res.data.user.address;
            // ✅ 在这里调用 switchllevel，传入 userLevel  
            const userLevelRaw = res.data.user.userLevel;
            switchllevel(String(userLevelRaw)); // 确保传入的是字符串，如 '0'
            console.log(res.data.user.area.split("/")[0]);
            console.log(res.data.user.area.split("/")[1]);
            data.data.forEach(cou => {
                if (cou.state_code == res.data.user.area.split("/")[0]) {
                    console.log("国家:", cou.name);
                    userInfo.value.contry = cou.name;
                    cou.states.forEach(st => {
                        if (st.state_code == res.data.user.area.split("/")[1]) {
                            console.log("州:", st.name);
                            userInfo.value.addresszhou = st.name;
                        }
                    })

                }
            })


        }

    })
}
onMounted(() => {
    console.log(Decrypt("yOpSIxe0JqgBsx1O3pqWzsGcTNXNxXel06r7/HEQbPIMsEdTLsOQZkY4UTmyKKXlt6txHmHmerqwg5p0ijVSWGJRoBcrYb0A/dWZa1fOss8730qmcmudyxKYk34jmj7MxqHgGG5djPgQtb9dBn4TMg=="));

    getuserbasicdatafun()
    console.log("data", data.data);
    datasel.value = data.data;
    // 将数据转换为{国家名: [州数组]}的格式
    const tempCountryStates = {};
    data.data.forEach(country => {
        tempCountryStates[country.name] = country.states || [];
    });
    countryStates.value = tempCountryStates;
});

// 处理国家变化事件
const handleCountryChange = (countryName) => {
    userInfo.value.addresszhou = ''; // 重置已选的州
    states.value = countryStates.value[countryName] || []; // 更新州列表
};
function closechange(){
    router.push("/")
}
function changeperson() {
    let tool = true
    if (userInfo.value.nickname == "") {
        tool = false;
        ElMessage.error("Please enter a nickname")
        return;
    }
    console.log(userInfo.value)
    const selectedCountry = userInfo.value.contry;
    const selectedState = userInfo.value.addresszhou;
    const selectedCountryData = data.data.find(country => country.name === selectedCountry);
    const selectedStateData = selectedCountryData?.states?.find(state => state.name === selectedState);

    if (selectedCountry && selectedState) {
        const countryStateCode = selectedCountryData.state_code;
        const stateStateCode = selectedStateData?.state_code;
        console.log("国家 state_code:", countryStateCode);
        console.log("州 state_code:", stateStateCode);
        // 在这里你可以将获取到的 state_code 进行进一步处理，比如发送到服务器


        let requestData = {
            nickname: userInfo.value.nickname,
            gender: userInfo.value.gender,
            area: `${countryStateCode}/${stateStateCode}`,
            address: userInfo.value.account,
        }
        personcenterEditInfo(requestData).then(res => {
            console.log(res)
            if (res.code == 200) {
                console.log("修改成功")
                basicInfo.value.nickname = userInfo.value.nickname;  // 更新昵称
                basicInfo.value.phone = userInfo.value.phone;        // 更新手机号（如果可编辑）
                basicInfo.value.email = userInfo.value.email;        // 更新邮箱（如果可编辑）
                basicInfo.value.belongingrole = userInfo.value.belongingrole;  // 更新角色（如果可编辑）
                getuserbasicdatafun();
                getuserbasicdatafun()
                // router.push("/")
            } else {
                console.log("修改失败")
            }
        })

    } else {
        console.log("请选择完整的国家/地区信息");
    }



}
function close() {
    changepassword.value.oldpassword = "",
        changepassword.value.newpassword = "",
        changepassword.value.newpasswordagain = ""
}
</script>

<style scoped>
.user-profile-container {
    padding: 20px;
    max-width: 1000px;
    margin: 0 auto;
}

.profile-card {
    padding: 20px;
}

.title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 20px;
}

.profile-tabs {
    margin-bottom: 20px;
}

.form-section {
    padding: 0 10px;
}

.el-form-item {
    /* margin-bottom: 18px; */
}

.el-input__wrapper {
    width: 10px
}

.el-button {
    margin: 10px 0 0 50px;
}

.hang-row {
    display: flex;
    justify-content: space-between;
}
</style>